package org.mat.ipaas.ucenter.service.modules.message.controller;

import java.util.Arrays;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.api.dto.message.Message;
import org.mat.ipaas.ucenter.biz.common.system.api.ISysBaseAPI;
import org.mat.ipaas.ucenter.service.api.message.SysMessageTemplateRestAPI;
import org.mat.ipaas.ucenter.service.dto.message.entity.MsgParamsDTO;
import org.mat.ipaas.ucenter.service.dto.message.entity.SysMessageTemplateDTO;
import org.mat.ipaas.ucenter.service.modules.MatController;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.common.util.oConvertUtils;
import org.mat.ipaas.ucenter.biz.modules.message.entity.MsgParams;
import org.mat.ipaas.ucenter.biz.modules.message.entity.SysMessageTemplate;
import org.mat.ipaas.ucenter.biz.modules.message.service.ISysMessageTemplateService;
import org.mat.ipaas.ucenter.biz.modules.message.util.PushMsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.extern.slf4j.Slf4j;

/**
 * 消息模板
 * @Sate: 2019-04-09
 * @Version: V1.0
 */
@Slf4j
@RestController
@RequestMapping("/sys/message/sysMessageTemplate")
public class SysMessageTemplateController extends MatController<SysMessageTemplate, ISysMessageTemplateService> implements SysMessageTemplateRestAPI {

    @Autowired
    private ISysMessageTemplateService sysMessageTemplateService;
    @Autowired
    private PushMsgUtil pushMsgUtil;

    @Autowired
    private ISysBaseAPI sysBaseApi;

    /**
     * 分页列表查询
     *
     * @param sysMessageTemplateDTO
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public MatApiResponse<?> queryPageList(@SpringQueryMap SysMessageTemplateDTO sysMessageTemplateDTO,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        SysMessageTemplate sysMessageTemplate = toSysMessageTemplate(sysMessageTemplateDTO);

        QueryWrapper<SysMessageTemplate> queryWrapper = QueryGenerator.initQueryWrapper(sysMessageTemplate, req.getParameterMap());
        Page<SysMessageTemplate> page = new Page<SysMessageTemplate>(pageNo, pageSize);
        IPage<SysMessageTemplate> pageList = sysMessageTemplateService.page(page, queryWrapper);
        return MatApiResponse.success(pageList);
    }

    /**
     * 添加
     *
     * @param sysMessageTemplateDTO
     * @return
     */
    @PostMapping(value = "/add")
    public MatApiResponse<?> add(@RequestBody SysMessageTemplateDTO sysMessageTemplateDTO) {
        SysMessageTemplate sysMessageTemplate = toSysMessageTemplate(sysMessageTemplateDTO);

        sysMessageTemplateService.save(sysMessageTemplate);
        return MatApiResponse.success("添加成功！");
    }

    /**
     * 编辑
     *
     * @param sysMessageTemplateDTO
     * @return
     */
    @PutMapping(value = "/edit")
    public MatApiResponse<?> edit(@RequestBody SysMessageTemplateDTO sysMessageTemplateDTO) {
        SysMessageTemplate sysMessageTemplate = toSysMessageTemplate(sysMessageTemplateDTO);

        sysMessageTemplateService.updateById(sysMessageTemplate);
        return MatApiResponse.success("更新成功！");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public MatApiResponse<?> delete(@RequestParam(name = "id", required = true) String id) {
        sysMessageTemplateService.removeById(id);
        return MatApiResponse.success("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public MatApiResponse<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.sysMessageTemplateService.removeByIds(Arrays.asList(ids.split(",")));
        return MatApiResponse.success("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public MatApiResponse<?> queryById(@RequestParam(name = "id", required = true) String id) {
        SysMessageTemplate sysMessageTemplate = sysMessageTemplateService.getById(id);
        return MatApiResponse.success(sysMessageTemplate);
    }

    /**
     * 导出excel
     */
    @GetMapping(value = "/exportXls")
    public ModelAndView exportXls(SysMessageTemplateDTO sysMessageTemplateDTO) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        SysMessageTemplate sysMessageTemplate = toSysMessageTemplate(sysMessageTemplateDTO);

        return super.exportXls(request, sysMessageTemplate, SysMessageTemplate.class, "推送消息模板");
    }

    /**
     * excel导入
     *
     * @return
     */
    @PostMapping(value = "/importExcel")
    public MatApiResponse<?> importExcel() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();

        return super.importExcel(request, response, SysMessageTemplate.class);
    }

    /**
     * 发送消息
     */
    @PostMapping(value = "/sendMsg")
    public MatApiResponse<SysMessageTemplateDTO> sendMessage(@RequestBody MsgParamsDTO msgParamsDTO) {
        MatApiResponse<SysMessageTemplate> matApiResponse = new MatApiResponse<SysMessageTemplate>();
        MsgParams msgParams = toMsgParams(msgParamsDTO);

        try {
            Message md = new Message();
            md.setToAll(false);
            md.setTitle("消息发送测试");
            md.setTemplateCode(msgParams.getTemplateCode());
            md.setToUser(msgParams.getReceiver());
            md.setType(msgParams.getMsgType());
            String testData = msgParams.getTestData();
            if (oConvertUtils.isNotEmpty(testData)) {
                Map<String, Object> data = JSON.parseObject(testData, Map.class);
                md.setData(data);
            }
            sysBaseApi.sendTemplateMessage(md);
            return matApiResponse.success().setMessage("消息发送成功！");
        } catch (Exception e) {
            log.error("发送消息出错", e.getMessage());
            return matApiResponse.fail("发送消息出错！");
        }
    }

    private MsgParams toMsgParams(MsgParamsDTO msgParamsDTO) {
        if (msgParamsDTO == null) {
            return null;
        }
        MsgParams msgParams = new MsgParams();
        msgParams.setMsgType(msgParamsDTO.getMsgType());
        msgParams.setReceiver(msgParamsDTO.getReceiver());
        msgParams.setTemplateCode(msgParamsDTO.getTemplateCode());
        msgParams.setTestData(msgParamsDTO.getTestData());
        return msgParams;
    }


    private SysMessageTemplate toSysMessageTemplate(SysMessageTemplateDTO sysMessageTemplateDTO) {
        if (sysMessageTemplateDTO == null) {
            return null;
        }
        SysMessageTemplate sysMessageTemplate = new SysMessageTemplate();
        sysMessageTemplate.setId(sysMessageTemplateDTO.getId());
        sysMessageTemplate.setCreateBy(sysMessageTemplateDTO.getCreateBy());
        sysMessageTemplate.setCreateTime(sysMessageTemplateDTO.getCreateTime());
        sysMessageTemplate.setUpdateBy(sysMessageTemplateDTO.getUpdateBy());
        sysMessageTemplate.setUpdateTime(sysMessageTemplateDTO.getUpdateTime());
        sysMessageTemplate.setTemplateCode(sysMessageTemplateDTO.getTemplateCode());
        sysMessageTemplate.setTemplateName(sysMessageTemplateDTO.getTemplateName());
        sysMessageTemplate.setTemplateContent(sysMessageTemplateDTO.getTemplateContent());
        sysMessageTemplate.setTemplateTestJson(sysMessageTemplateDTO.getTemplateTestJson());
        sysMessageTemplate.setTemplateType(sysMessageTemplateDTO.getTemplateType());
        sysMessageTemplate.setUseStatus(sysMessageTemplateDTO.getUseStatus());
        return sysMessageTemplate;
    }

}
